# -*- coding: utf-8 -*-
# @Time        : 2023/11/18
# @Author      : keyan.kalami
# @Email       : yclu@aioaiofm.ac.cn
# @File        : draw.py
# @Project     : NovaPrograms
# @Description : 获取并处理NOAA数据集的主程序

import numpy as np
import os
import sys
import json
import sqlite3
from urllib.parse import urljoin
from lxml import etree
import requests
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt 
import matplotlib as mpl
mpl.use('Agg')

import warnings
warnings.filterwarnings('ignore')

with open('/root/Programs/NovaPrograms/set/_ads.json', 'r', encoding='utf-8') as file:  
    VALUE_SETS = json.load(file)

class DRAW:
    def __init__(self):
        self.lons = []
        self.lats = []
        self.altitudes = []
        #create session
        self.s = requests.Session()
        #configuration database
        self.conn = sqlite3.connect(VALUE_SETS["DB_NAME"])
        self.cursor = self.conn.cursor()
    
    def draw_back_traj(self):

        # 执行SELECT查询并获取结果
        self.cursor.execute('SELECT latitude FROM Traj_Table ORDER BY data ASC')
        result1 = self.cursor.fetchall()
        # 将结果存储在列表中
        latitude = [row[0] for row in result1[::10]]

        self.cursor.execute('SELECT longitude FROM Traj_Table ORDER BY data ASC')
        result2 = self.cursor.fetchall()
        # 将结果存储在列表中
        longitude = [row[0] for row in result2[::10]]

        self.cursor.execute('SELECT height FROM Traj_Table ORDER BY data ASC')
        result3 = self.cursor.fetchall()
        # 将结果存储在列表中
        height = [row[0] for row in result3[::10]]

        # 创建画布和子图对象
        fig, ax = plt.subplots()

        # 绘制折线图
        ax.plot(latitude, longitude)

        plt.savefig("/root/Programs/NovaPrograms/datas/photo/test.pdf")

    def draw_traj_basemap(self,add_size:float,space:int):
        # 执行SELECT查询并获取结果
        self.cursor.execute('SELECT latitude FROM Traj_Table ORDER BY data ASC')
        result1 = self.cursor.fetchall()
        # 将结果存储在列表中
        longitude = [row[0] for row in result1[::2]]

        self.cursor.execute('SELECT longitude FROM Traj_Table ORDER BY data ASC')
        result2 = self.cursor.fetchall()
        # 将结果存储在列表中
        latitude = [row[0] for row in result2[::2]]

        self.cursor.execute('SELECT height FROM Traj_Table ORDER BY data ASC')
        result3 = self.cursor.fetchall()
        # 将结果存储在列表中
        height = [row[0] for row in result3[::2]]

        lon_min, lon_max = min(longitude), max(longitude)
        lat_min, lat_max = min(latitude), max(latitude)

        # 创建Basemap对象
        map = Basemap(projection='merc', llcrnrlon=(lon_min-add_size), llcrnrlat=(lat_min-add_size), urcrnrlon=(lon_max+add_size), urcrnrlat=(lat_max+add_size), resolution='l')
        
        # 绘制海岸线和国家边界线
        map.drawcoastlines()
        map.drawcountries()

        # 绘制经纬度网格线
        map.drawmeridians(range(int(lon_min), int(lon_max), space), labels=[0, 0, 0, 1])
        map.drawparallels(range(int(lat_min), int(lat_max), space), labels=[1, 0, 0, 0])

        # 绘制轨迹线
        x, y = map(longitude, latitude)

        # 绘制轨迹线，并根据海拔高度使用不同的颜色
        sc = map.scatter(x, y, c=height, cmap=plt.get_cmap('YlOrRd'), s=20, marker='o', edgecolors='k', alpha=0.9, vmin=50, vmax=300)

        # 标记起点为黑色
        map.scatter(x[0], y[0], color='yellow', s=50, marker='o', edgecolors='k')

        # 标记终点为黄色
        map.scatter(x[-1], y[-1], color='yellow', s=50, marker='o', edgecolors='k')

        # 添加颜色条
        cbar = map.colorbar(sc, location='right', pad="20%")
        cbar.set_label('Elevation (m)')

        map.plot(x, y, linestyle='dashed', color='blue', alpha=0.3)
        plt.savefig("/root/Programs/NovaPrograms/datas/photo/traj2.pdf")


    def __del__(self):
        # 关闭游标和数据库连接
        self.cursor.close()
        self.conn.close()